package com.gaofans.nrpc.common.filter;

import com.gaofans.nrpc.common.protocol.Message;
import com.gaofans.nrpc.common.processor.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 默认的过滤器链实现
 * @author GaoFans
 */
public class DefaultFilterChain<T extends Message> implements FilterChain<T>{

    private final int index;

    private final List<? extends Filter<T>> filters;

    private final RpcContext context;

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultFilterChain.class);

    public DefaultFilterChain(List<? extends Filter<T>> filters, RpcContext context) {
        this.filters = filters;
        this.index = 0;
        this.context = context;
    }

    private DefaultFilterChain(DefaultFilterChain<T> parent, int index,RpcContext context) {
        this.filters = parent.getFilters();
        this.index = index;
        this.context = context;
    }

    public List<? extends Filter<T>> getFilters() {
        return filters;
    }

    @Override
    public Mono<Void> doFilter(T request) {
        return Mono.defer(() -> {
            if (this.index < filters.size()) {
                Filter<T> filter = filters.get(this.index);
                FilterChain<T> chain = new DefaultFilterChain<T>(this, this.index + 1,context);
                LOGGER.debug("执行过滤器链 message:{}",request.getSequenceId());
                return filter.filter(request, chain);
            }else {
                return Mono.empty();
            }
        });
    }

    @Override
    public RpcContext context() {
        return context;
    }
}
